<?php
namespace app\hotback\controller;
use app\common\enum\OrderEnum;
use think\Db;
class Order extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}


	/**
	 * 服务列表
	 */
	public function index()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();

			if(!empty($params['page']) && !empty($params['limit']))
			{

                $map = [];
				if(!empty($params['order_no']))
				{
					$map['o.order_no'] = $params['order_no'];
				}
                if(!empty($params['real_name']))
                {
                    $map['t.real_name'] = $params['real_name'];
                }
                if(!empty($params['nickname']))
                {
                    $map['t.nickname'] = $params['nickname'];
                }
                if(!empty($params['mobile']))
                {
                    $map['a.mobile'] = $params['mobile'];
                }
                if(!empty($params['status']))
                {
                    $map['o.status'] = $params['status'];
                }
                if(!empty($params['proxy_id']))
                {
                    $proxy = Db::name('proxy')->where('proxy_id',$params['proxy_id'])->find();
                    if ($proxy['is_xian'] == 1){
                        $map['o.qu'] = $proxy['qu'];
                    }else{
                        $not = Db::name('proxy')->where('shi',$proxy['shi'])->where('is_xian',1)->column('qu');
                        $map['o.shi'] = $proxy['shi'];
                        $map['o.qu'] = ['not in',$not];

                    }
                }

                if (!empty($params['expire_start_time']))
                    $map['o.add_time'] = ['>=', strtotime($params['expire_start_time'])];

                if (!empty($params['expire_end_time']))
                    $map['o.add_time'] = ['<', strtotime($params['expire_end_time'])];
                if (!empty($params['expire_end_time']) && !empty($params['expire_start_time']))
                    $map['o.add_time'] = ['between', strtotime($params['expire_start_time']).','.strtotime($params['expire_end_time'])];
                /*
                $count = Db::name('Order')->where($map)->count();
				$list_data = Db::name('Order')->where($map)->order('id desc')->limit(($params['page']-1)*$params['limit'],$params['limit'])->select();
                */



                $count = Db::table('jx_order')
                    ->alias('o')
                    ->where($map)
//                    ->where('techn_id','<>',299)
                    ->join('techn t','o.techn_id = t.id')
                    ->join('user u','t.user_id = u.id')
                    //->join('order_detail d','o.id = d.order_id')
                    ->join('order_address a','o.id = a.order_id')
                    ->order('o.id desc')
                    ->field('o.*,t.real_name,a.mobile,u.nickname')
                    ->count();


                $list_data = Db::table('jx_order')
                    ->alias('o')
                    ->where($map)
//                    ->where('techn_id','<>',299)
                    ->join('techn t','o.techn_id = t.id')
                    ->join('user u','t.user_id = u.id')
                    //->join('order_detail d','o.id = d.order_id')
                    ->join('order_address a','o.id = a.order_id')
                    ->limit(($params['page']-1)*$params['limit'],$params['limit'])
                    ->order('o.id desc')
                    ->field('o.*,t.real_name,t.nickname as tnickname,a.mobile,a.name,u.nickname,t.mobile as t_mobile,a.city_name,a.county_name')
                    ->select();
// echo Db::table('jx_order')
//                     ->alias('o')
//                     ->where($map)
//                     ->join('techn t','o.techn_id = t.id')
//                     ->join('user u','t.user_id = u.id')
//                     //->join('order_detail d','o.id = d.order_id')
//                     ->join('order_address a','o.id = a.order_id')
//                     ->limit(($params['page']-1)*$params['limit'],$params['limit'])
//                     ->order('o.id desc')
//                     ->field('o.*,t.real_name,t.nickname as tnickname,a.mobile,a.name,u.nickname')->fetchsql(true)
//                     ->select();exit;

                if(!empty($list_data))
				{
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//编辑url
						$list_data[$key]['view_url'] = url('order/view', ['id' => $value['id']]);
                        $list_data[$key]['add_time'] = date("Y-m-d H:i:s",$value['add_time']);
//                        if(!empty($value['service_time'])){
//                            if(!empty($value['over_time'])){
//                                $list_data[$key]['service_time'] = date("Y-m-d H:i:s",$value['service_time']).' - '.date("H:i:s",$value['over_time']);
//                            }else{
//                                $list_data[$key]['service_time'] = date("Y-m-d H:i:s",$value['service_time']).' - '.'服务未结束';
//                            }
                             
//                        }else{
//                            $list_data[$key]['service_time'] = date("Y-m-d H:i:s",$value['pre_start_time'])."<br>".date("H:i:s",$value['pre_end_time']);
                            $list_data[$key]['service_time'] = date("Y-m-d",$value['pre_start_time'])."                     ".date("H:i:s",$value['pre_start_time']).'-'.date("H:i:s",$value['pre_end_time']);
                            // $list_data[$key]['service_time'] = '服务未开始';
//                        }
                        $order_detail = Db::name('OrderDetail')->where(['order_id'=>$value['id'],'showtype'=>1])->select();
                        $refund_time = Db::name('refund_log')->where('order_id',$value['id'])->value('add_time');
                        $list_data[$key]['refund_time'] = empty($refund_time) ? '-' : date('Y-m-d H:i:s',$refund_time);
                        $list_data[$key]['payment'] = Db::name('pay_log')->where('order_id',$value['id'])->value('payment_name').'支付';
                        $title = '';

                        foreach ($order_detail AS $k=>$v) {
                            $msgs='';
            			    if($v['type']==1){
            			        $msgs='(加钟)';
            			    }
            			    $upmsgs='';
            			    if($v['uptype']==1){
            			        $upmsgs='(升级)';
            			    }

                            $title .= $v['title'].'-'.$v['duration'].'分钟'.$msgs.$upmsgs."(".$v['price']."*".$v['buy_number'].")  &nbsp;&nbsp;";
                        }


                        $list_data[$key]['title'] =  $title;
                        $list_data[$key]['address'] =  $value['city_name'].$value['county_name'];

                        $list_data[$key]['status'] = OrderEnum::getOrderStatusDesc($value['status']);

					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{

            $money['all'] = Db::name('order')
                ->alias('a')
//                ->join('balance b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
//                ->where('b.status','<>',2)
                ->sum('a.pay_price');

            $month = date('m',time())-1;
            $min_month = strtotime(date('Y-',time()).$month.'-1 00:00:00');
            $max_month = strtotime(date('Y-',time()).date('m',time()).'-1 00:00:00')-1;
            $day = date('Y-m-d',time()-86400);
            $min_day = strtotime(date($day.' 00:00:00'));
            $max_day = strtotime(date($day.' 23:59:59'));
            $money['month'] = Db::name('order')
                ->alias('a')
//                ->join('balance b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
                ->where('a.pay_time','>=',$min_month)
                ->where('a.pay_time','<',$max_month)
                ->sum('a.pay_price');

            $money['day'] = Db::name('order')
                ->alias('a')
                ->join('pay_log b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('b.payment','<>','MoneyPay')
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
                ->where('a.pay_time','>=',$min_day)
                ->where('a.pay_time','<',$max_day)
                ->sum('b.total_price');

            $log_all = Db::name('pay_log')
                ->where('payment','<>','MoneyPay')
                ->where('add_time','>=',$min_day)
                ->where('add_time','<',$max_day)
                ->sum('total_price');
            $log_tui = Db::name('refund_log')
                ->where('payment','<>','MoneyPay')
                ->where('add_time','>=',$min_day)
                ->where('add_time','<',$max_day)
                ->sum('refund_price');
            $money['day'] = $log_all - $log_tui;
            $money['all_car'] = Db::name('order')
                ->alias('a')
//                ->join('balance b','a.id = b.order_id')
//                ->where('b.balance_type','=',2)
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
//                ->where('b.status','<>',2)
                ->sum('a.travel_price');
            $money['month_car'] = Db::name('order')
                ->alias('a')
//                ->join('balance b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
//                ->where('b.balance_type','=',2)
                ->where('a.pay_time','>=',$min_month)
                ->where('a.pay_time','<',$max_month)
                ->sum('a.travel_price');
            $money['day_car'] = Db::name('order')
                ->alias('a')
//                ->join('balance b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
//                ->where('b.balance_type','=',2)
                ->where('a.pay_time','>=',$min_day)
                ->where('a.pay_time','<',$max_day)
                ->sum('a.travel_price');
            $money['all_techn'] = Db::name('order')
                ->alias('a')
                ->join('balance b','a.id = b.order_id')
                ->where('b.balance_type','=',1)
                ->where('b.identity_type','=','techn')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
                ->where('b.status','<>',2)
                ->sum('b.yes_money');
            $money['month_techn'] = Db::name('order')
                ->alias('a')
                ->join('balance b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
                ->where('b.balance_type','=',1)
                ->where('b.identity_type','=','techn')
                ->where('b.add_time','>=',$min_month)
                ->where('b.add_time','<',$max_month)
                ->sum('b.yes_money');
            $money['day_techn'] = Db::name('order')
                ->alias('a')
                ->join('balance b','a.id = b.order_id')
//                ->where('a.status','in',[1,2,3,4,5,6])
                ->where('a.status','=',6)
                ->where('a.techn_id','<>',299)
                ->where('b.balance_type','=',1)
                ->where('b.identity_type','=','techn')
                ->where('b.add_time','>=',$min_day)
                ->where('b.add_time','<',$max_day)
                ->sum('b.yes_money');
            $login_info = $_SESSION['think'];
            if ($login_info['admin']['username'] == 'admin')
			$this->assign('money',$money);

            $proxy_list = Db::name('proxy')->where('is_delete_time',0)->select();
            $this->assign('proxy_list',$proxy_list);

			return $this->fetch();
		}
	}

	/**
	 * 服添添加/修改 页面
	 */
	public function saveinfo()
	{
		// 参数
		$params = input();
		$info = [];
		if(!empty($params['id']))
		{
			//查询
			$info = Db::name('service')->where(['id' => $params['id']])->find();
			
			if(empty($info['service_time'])){
                $info['service_time'] = $info['pre_start_time'];
            }
            if(empty($info['over_time'])){
                $info['over_time'] = $info['pre_end_time'];
            }
		}
		
		
		$this->assign('info',$info);

		//编辑器文件存放地址
		$this->assign('editor_path_type', 'service');
		return $this->fetch();
	}


    public function view() {
        // 参数
        $params = input();
        $info = [];
        $order_detail = [];
        if(!empty($params['id']))
        {
            //查询
            $order_id = $params['id'];

            $info = Db::table('jx_order')
                ->alias('o')
                ->join('techn t','o.techn_id = t.id')
                ->join('user u','t.user_id = u.id')
                //->join('order_detail d','o.id = d.order_id')
                ->join('order_address a','o.id = a.order_id')
                ->where("o.id = '$order_id'")
                ->order('o.id desc')
                ->field('o.*,t.real_name,t.nickname as tusername,t.work_img,a.mobile,a.name,a.province_name,a.city_name,a.county_name,a.address,a.address_des,u.nickname')
                ->find();

            $order_detail = Db::name('OrderDetail')->where("order_id = '$order_id'")->select();

            $status_history = Db::name('OrderStatusHistory')->where("order_id = '$order_id' AND identity_type = 'techn'")->order('new_status asc')->select();

			if($info['local_pre_start_time'] != 0){
                $info['service_time'] = $info['local_pre_start_time'];
            }else{
                $info['service_time'] = $info['pre_start_time'];

            }
            if($info['local_pre_end_time'] != 0){
                $info['over_time'] = $info['local_pre_end_time'];
            }else{
                $info['over_time'] = $info['pre_end_time'];

            }
        }
        $this->assign('info',$info);
        //编辑器文件存放地址
        $this->assign('editor_path_type', 'service');
        $this->assign('order_detail',$order_detail);
        $this->assign('status_history',$status_history);
//        halt($status_history);
        return $this->fetch();
    }


	/**
	 * 服务添加/修改
	 */
	public function save()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			$validate = $this->validate(
				$params,
				[
					'title' => 'require|unique:service,is_delete_time=0&title='.$params['title'],
					'images' => 'require',
					'carousels' => 'require',
					'price' => ['require', 'regex' => '^([0-9]{1}\d{0,6})(\.\d{1,2})?$', 'egt' => 0.01],
					'original_price' => ['require', 'regex' => '^([0-9]{1}\d{0,6})(\.\d{1,2})?$'],
					'sales_unreal' => 'integer|egt:0',
					'duration' => 'require|integer|egt:1',
					'introduce' => 'require',
					'taboos' => 'require',
					'notice' => 'require'
				],
				[
					'title.require' => '请输入服务名称',
					'title.unique' => '名称已存在',
					'images.require' => '请上传封面图',
					'carousels.require' => '请上传轮播图',
					'price.require' => '请输入服务价格',
					'price.regex' => '服务价格有误',
					'price.egt' => '服务价格大于等于0.01',
					'original_price.require' => '请输入服务原价',
					'original_price.regex' => '服务原价有误',
					'sales_unreal.integer' => '虚拟销量为整数',
					'sales_unreal.egt' => '虚拟销量大于等于0',
					'duration.require' => '请输入服务时长',
					'duration.integer' => '服务时长为整数',
					'duration.egt' => '服务时长大于等于1',
					'introduce.require' => '请输入项目介绍',
					'taboos.require' => '请输入禁忌说明',
					'notice.require' => '请输入下单须知'
				]
			);
			if(true !== $validate)
			{
				echo json_encode(['code' => -1, 'msg' => $validate]);
				exit();
			}
			//基础数据
			$data = [
				'title' => $params['title'],
				'sub_title' => $params['sub_title'],
				'images' => $params['images'],
				'carousels' => implode(",", $params['carousels']),
				'price' => $params['price'],
				'original_price' => $params['original_price'],
				'sales_unreal' => intval($params['sales_unreal']),
				'sales_total' => Db::raw('sales_actual+'.intval($params['sales_unreal'])),
				'duration' => $params['duration'],
				'introduce' => $params['introduce'],
				'taboos' => $params['taboos'],
				'notice' => $params['notice'],
				'is_shelves' => isset($params['is_shelves']) ? intval($params['is_shelves']) : 0,
				'sort' => isset($params['sort']) ? intval($params['sort']) : 0
			];
			// 添加/编辑
			if(empty($params['id']))
			{
				$data['add_time'] = time();
        		$data['upd_time'] = time();
        		$service_id = Db::name('service')->insertGetId($data);
			}else
			{
				$data['upd_time'] = time();
				if(Db::name('service')->where(['id'=>intval($params['id'])])->update($data))
				{
					$service_id = $params['id'];
				}
			}
			//是否成功
			if(isset($service_id) && $service_id > 0)
			{
				$result['code'] = 0;
				$result['msg'] = "操作成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "操作失败";
			}
		}
		echo json_encode($result);
	}

	/**
	 * 服务删除
	 */
	public function delete()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			$data = [
				'is_delete_time' => time(),
				'upd_time' => time()
			];
			if(Db::name('service')->where(['id' => intval($params['id'])])->update($data))
			{
				$result['code'] = 0;
				$result['msg'] = "删除成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "删除失败";
			}
		}
		echo json_encode($result);
	}
}